#
#===============================================================================
#
#         FILE:  Time.pm
#
#  DESCRIPTION:  
#
#        FILES:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:   (), <>
#      COMPANY:  
#      VERSION:  1.0
#      CREATED:  04/20/2010 06:06:11 PM GMT
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;

package GoogPl::Time;

use XML::Simple;
use LWP::UserAgent;
use URI::Escape qw(uri_escape);
use JSON qw(decode_json);
use DateTime;

sub register {
    my $self = shift;

    return ('cmd' => 'time', 'pat' => '^!time\s+(.*)');
}

sub help {
    my $self = shift;
    
    return ('Lookup time and timezone information');
}

sub process_command {
    my $self = shift;
    my ($kernel, $sender, $nickhost, $target, $msgtxt, %conf) = @_;

    $msgtxt =~ /^!time\s+(.*)/;

    my $arg = $1;

    my $ua = LWP::UserAgent->new;
    my $resp = $ua->get("http://maps.google.com/maps/api/geocode/xml?sensor=false&address=".uri_escape($arg));

    if( ! $resp->is_success ) {
	return;
    }

    my $xs = XML::Simple->new;

    my $xml = $xs->XMLin($resp->decoded_content);

    my $result;
    if (ref($xml->{'result'}) eq 'ARRAY') {
	$result = $xml->{'result'}[0];
    } else {
	$result = $xml->{'result'};
    }
    my ($lat,$lng) = ($result->{'geometry'}{'location'}{'lat'},
	    $result->{'geometry'}{'location'}{'lng'});

    $resp = $ua->get("http://www.google.com/ig/timezone?lat=$lat&lng=$lng");
    if( ! $resp->is_success ) {
	return;
    }

    my $json = $resp->decoded_content;
    $json =~ s/'/"/g;
    my $tz = decode_json($json);
    my $d = DateTime->now;
    $d->set_time_zone(tzoffset($tz->{'rawOffset'} + $tz->{'dstOffset'}));
    $kernel->post($sender => privmsg => $target =>
	    sprintf('The time in %s is %s GMT%s',
		$result->{'formatted_address'}, $d, $d->time_zone->name));

}

sub tzoffset {
    my $offset = shift;
    $offset /= 3600000;

    my $neg = $offset < 0;
    my $hr = abs(int($offset));
    my $mn = $offset - int($offset);

    return sprintf('%s%02d%02d', $neg ? '-' : '+', $hr, $mn);
}

1;
